package com.yunhe.dao.daoimpl;

import com.yunhe.dao.CourseDao;
import com.yunhe.enity.Course;
import com.yunhe.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CourseDaoImpl implements CourseDao {
    QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());

    @Override
    public int addCourse(Course course) {
        String sql = "insert into course values(null,?,?,?,?,?,?,?,now())";
        try {
            return qr.update(sql, course.getCourseName(), course.getDescs(), course.getCourseType(), course.getCourseImage()
                    , course.getCourseVideo(), course.getCoursePrice(), course.getStatus());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Course> findCount(String sql, ArrayList<Object> courses) {
        try {
            return qr.query(sql, new BeanListHandler<Course>(Course.class), courses.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Course> findByLimit(String sql, ArrayList<Object> courses, int cpage, int size) {
        sql +="   limit ?,?";
        int start =(cpage-1)*size;
        courses.add(start);
        courses.add(size);
        try {
            return qr.query(sql, new BeanListHandler<Course>(Course.class), courses.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int deleteAll(String cid) {
        System.out.println(cid);
        String sql ="delete from course where cid in ("+cid+")";
        try {
            return qr.update(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int updateCourse(Course course) {
        String sql = "update course set courseName=?,descs=?,courseType=?" +
                ",courseImage=?,courseVideo=?,coursePrice=?,status=? where cid=?";
        try {
            return qr.update(sql, course.getCourseName(), course.getDescs(), course.getCourseType(), course.getCourseImage()
                    , course.getCourseVideo(), course.getCoursePrice(), course.getStatus(),course.getCid());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Course findCourByid(Course course) {
        String sql = "select  courseImage,courseVideo from course where cid=?";
        try {
            return qr.query(sql, new BeanHandler<Course>(Course.class), course.getCid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
